from bs4 import BeautifulSoup
from common import get_structured_text, save_file
from common import setup_session, save_file, get_response


def resolveManagementTeam(obj):
    href = obj["href"]
    title = obj["title"]
    content = obj["content"]
    soup = BeautifulSoup(content, 'html.parser')
    items = soup.find_all('li', class_="clearfix wow slideInUp")

    result = []

    for item in items:
        headImg = item.find('img')['src']
        name = item.find('h3').text.strip()
        descNode = item.find('div', class_="box")
        desc = get_structured_text(descNode)
        result.append({"headImg": headImg, "name": name, "desc": desc})

    save_file(result, title + ".json")


def resolveTeachTeamOneSubject(obj):
    href = obj["href"]
    title = obj["title"]
    content = obj["content"]
    soup = BeautifulSoup(content, 'html.parser')
    items = soup.find_all('li', class_="clearfix wow slideInUp")

    result = []

    for item in items:
        headImg = item.find('img')['src']
        name = item.find('h3').text.strip()
        descNode = item.find('div', class_="box")
        desc = get_structured_text(descNode)
        result.append({"headImg": headImg, "name": name, "desc": desc})

    return result


def resolveTeachTeam(obj):
    href = obj["href"]
    title = obj["title"]
    content = obj["content"]
    session = obj["session"]
    soup = BeautifulSoup(content, 'html.parser')

    div = soup.find('div', class_='side fl')
    teaching_team = div.find('a', text="教学团队").parent
    print("teaching_team:", teaching_team.prettify())

    if teaching_team:
        # 找到所有子 dd 中的 a 标签
        dl = teaching_team.find('dl')
        team_links = dl.find_all('a')

        # 提取每个 a 标签的文本和链接
        for link in team_links:
            group_name = link.text.strip()
            group_url = link.get('href')
            print(group_name + ' : ' + group_url)

            results = []
            pageIndex = 0

            while True:
                pageIndex += 1
                targetURL = 'https://www.ghcis.com/' + group_url + "?page=" + str(pageIndex)
                response = get_response(session, targetURL)

                if response:
                    tempList = resolveTeachTeamOneSubject(
                        {"href": group_url, "title": group_name, "content": response.text, "session": session})
                    results += tempList
                    if len(tempList) >= 6:
                        continue
                break

            save_file(results, title + '_' + group_name + ".json")
